package org.richin.net.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpUtils {
	public static final int CONN_TIMEOUT = 5000;
    public static final int READ_TIMEOUT = 15000;

	public static Map<String, String[]> parseQueryString(String s) {
		String valArray[] = null;
		if (s == null)
			throw new IllegalArgumentException();
		Map<String, String[]> ht = new HashMap<String, String[]>();
		StringBuffer sb = new StringBuffer();
		String key;
		for (StringTokenizer st = new StringTokenizer(s, "&"); st.hasMoreTokens(); ht.put(key, valArray)) {
			String pair = st.nextToken();
			int pos = pair.indexOf('=');
			if (pos == -1)
				throw new IllegalArgumentException();
			key = parseName(pair.substring(0, pos), sb);
			String val = parseName(pair.substring(pos + 1, pair.length()), sb);
			if (ht.containsKey(key)) {
				String oldVals[] = (String[]) ht.get(key);
				valArray = new String[oldVals.length + 1];
				for (int i = 0; i < oldVals.length; i++)
					valArray[i] = oldVals[i];

				valArray[oldVals.length] = val;
			} else {
				valArray = new String[1];
				valArray[0] = val;
			}
		}

		return ht;
	}

	private static String parseName(String s, StringBuffer sb) {
		sb.setLength(0);
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			switch (c) {
			case 43: // '+'
				sb.append(' ');
				break;

			case 37: // '%'
				try {
					sb.append((char) Integer.parseInt(s.substring(i + 1, i + 3), 16));
					i += 2;
					break;
				} catch (NumberFormatException e) {
					throw new IllegalArgumentException();
				} catch (StringIndexOutOfBoundsException e) {
					String rest = s.substring(i);
					sb.append(rest);
					if (rest.length() == 2)
						i++;
				}
				break;

			default:
				sb.append(c);
				break;
			}
		}

		return sb.toString();
	}

	public static StringBuffer getRequestURL(HttpServletRequest req) {
		StringBuffer url = new StringBuffer();
		String scheme = req.getScheme();
		int port = req.getServerPort();
		String urlPath = req.getRequestURI();
		url.append(scheme);
		url.append("://");
		url.append(req.getServerName());
		if (scheme.equals("http") && port != 80 || scheme.equals("https") && port != 443) {
			url.append(':');
			url.append(req.getServerPort());
		}
		url.append(urlPath);
		return url;
	}

	/**
	 * gets the text content of the connection
	 *
	 * @param con
	 *          an open url connection
	 * @return
	 * @throws IOException
	 */
	public static String getTextContent(java.net.URLConnection urlConn) throws IOException {
		BufferedReader htmlPage = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

		StringBuffer contents = new StringBuffer();

		String line = "";
		while ((line = htmlPage.readLine()) != null) {
			contents.append(line);
		}
		htmlPage.close();
		return contents.toString();
	}
	   public static int doHeadUrl( String strUrl )
       {
               int output = -1;

               try
               {
                       org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
                       httpClient.getParams().setParameter("http.socket.timeout", CONN_TIMEOUT);

                       HttpHead method = new HttpHead( strUrl );
                       method.setHeader( "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; InfoPath.1)" );
                       method.getParams().setParameter("http.socket.timeout", READ_TIMEOUT);

                       HttpResponse response = httpClient.execute(method);
                       output = response.getStatusLine().getStatusCode();
               }
               catch( Exception e )
               {
                     e.printStackTrace();
               }

               return output;
       }

}
